
<template>
	<view>
		<view class="studyBox" @click="handelAuto">
			  <!-- <swiper :current="currentIndex" style="height: 520rpx;" :autoplay="isAutoplay"  @change="onSwiperChange" :interval="imageInterval"  ref="swiper"> -->
			      <swiper :current="currentIndex" style="height: 520rpx;" ref="swiper" @change="onSwiperChange">
					<swiper-item v-for="(item, index) in list" :key="index"  >
			          <image style="width: 100%;height: 100%;" :src="item" mode="scaleToFill" :lazy-load="true" ></image>
			        </swiper-item>
			      </swiper>
				<view class="controls_postion" v-if="!isPlaying">
				  <view :class="['left-back',{'hide':currentIndex <= 0}]" @click.stop="leftImg">
				    <text class="cuIcon-back"></text>
				  </view>
				  <view class="right-forword" v-if="currentIndex < list.length-1" @click.stop="rightImg">
				    <text class="cuIcon-right"></text>
				  </view>
				</view>
			  <view v-if="isPlaying" class="mask">
			    <text class="cuIcon-video controls"></text>
			   </view>
		</view>
		<!-- <audio :src="audioSrc" ref="audioPlayer" :controls="true" autoplay @ended="onAudioEnded" @play @pause></audio> -->
		<scroll-view scroll-x class="bg-white nav" scroll-with-animation :scroll-left="scrollLeft">
			<view class="cu-item" :class="index==current?'text-green cur':''" v-for="(item,index) in navData"
				:key="index" @tap="tabSelect" :data-id="index">
				{{item.name}}
			</view>
		</scroll-view>
		<swiper class="scroll-view-height" @change="swipeIndex" :current="current" :duration="300">
			<swiper-item>
				<scroll-view scroll-y class="scroll-view-height list-content">
					<view class="content_text">
						<view class="content_text_introductory">
							<view class="Lesson_box">
								<rich-text :selectable="true" :nodes="LessonList"></rich-text>
							</view>
						</view>
					</view>
				</scroll-view>
			</swiper-item>
			<swiper-item>
			<scroll-view scroll-y class="scroll-view-height list-content">
				<view class="content_text">
					<view class="content_text_introductory">
						<view class="description_box">	
							<text :user-select="true">{{description}}</text>
						</view>
					</view>
				</view>
			</scroll-view>
			</swiper-item>
			<swiper-item>
				<scroll-view scroll-y class="scroll-view-height list-content">
					<view class="content_text">
						<view class="content_text_introductory">
							<view class="pptContent" v-if="downloadUrl != ''">
								<view class="pptBox justify-center">
									<view class="pptImg">
										<img src="/static/img/780.jpg">
									</view>
									<button class="cu-btn round bg-red shadow margin-left-lg" @click="download">
										<view class="cuIcon-down" style="font-size: 20px;"></view>
										下载
									</button>
									
								</view>
							</view>
							
						</view>
					</view>
				</scroll-view>
			</swiper-item>
			<swiper-item>
				<scroll-view scroll-y class="scroll-view-height list-content">
					<view class="content_text">
						<view class="content_text_introductory">
							<view v-if="AudioVoiceList!=''">
							<view :class="['content_box',{ active: isActice == index }]" v-for="item,index in AudioVoiceList" :key="index" @click="handelVoice(item,index)">
								<view class="boxItem flex">
									<view class="imgBox">
										<img :src="item.detail.icon"/>
									</view>
									<view class="cont-right cu-chat margin-left-xs">
										<text>{{ item.detail.name }}</text>
										<view :class="item.detail.sex == '男' ? 'man':'woman'">成年{{item.detail.sex}}声</view>
									</view>
								</view>
								<text>推荐：{{item.detail.type}}</text>
							</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
		<login ref="login" @succ="succ"></login>
		<view class='tn-tabbar-height'></view>
		<tabbar></tabbar>
	</view>
</template>

<script>
	import { Buffer } from 'buffer';
	import { AudioVoice,CourseDetails,getAudioVoice} from '@/api/index.js'
	export default {
		data() {
			return {
				current: 0,
				scrollLeft: 0,
				list:[],
				isActice:0,
				navData: [
					{
						id: 1,
						name: "文稿"
					},
					{
						id: 2,
						name: "简介"
					},
					{
						id: 3,
						name: "课件"
					},
					{
						id: 4,
						name: "声音"
					},
					
				],
				// isAutoplay:true,
				audioSrc: '',//声音url
				AudioVoiceList:{},//声音
				description:'',//简介
				LessonList:'',//讲义
				chapter_id:0,
				course_id:0,
				downloadUrl:'',//ppt文档下载url
				audioCtx:'',//音频控制器 音频上下文对象
				isPlaying:false,
				totalDuration:0, //音频总时长
				// imageInterval: 5000, // 图片轮播间隔时间
				currentIndex: 0,  // 当前显示的图片索引
				timeAudio:0 ,//记录播放时长
				manualSwitchTimeout:null,
				i:0,
				prevIndex: 0, // 用于存储上一次的索引
				isDirection:'',
				prevCurrent:0,
				isPageVisible: true, // 页面是否可见
			};
		},
		onLoad(options) {
			this.chapter_id = options.chapter_id
			this.course_id = options.course_id
			if (this.audioCtx) {
				this.audioCtx.stop();
			    this.audioCtx.destroy()
			    this.audioCtx = null
			}
		},
		onHide() {
			console.log("我隐藏了");
			 this.isPageVisible = false;
			// 停止音频播放
			if (this.audioCtx) {
			  this.audioCtx.stop();
			  this.audioCtx.destroy()
			  this.audioCtx = null
			}
		},
		onShow(){
			this.isPageVisible = true;
			if (this.audioCtx) {
				this.audioCtx.stop();
			    this.audioCtx.destroy()
			    this.audioCtx = null
			}
			if (uni.getStorageSync('token')) {
				this.isLogin = true
			} else {
				  
				this.$nextTick(() => {
					this.$refs.login.modal = true;
				})
			}
				//获取课程详情
				this.getCourseDetails({course_id:this.course_id,chapter_id:this.chapter_id})
		},
		beforeDestroy() {
			this.isPageVisible = false;
			//清除定时器
			console.log("我销毁了");
			// 停止音频播放
			if (this.audioCtx) {
			  this.audioCtx.stop();
			  this.audioCtx.destroy()
			  this.audioCtx = null
			}
		},
		methods: {
			leftImg(){
				let num = this.list.length - 1
				if (this.currentIndex <= 0) {
					this.currentIndex = 0
				} else {
					this.currentIndex--
				}
			},
			rightImg(){
				let num = this.list.length - 1
				if (this.currentIndex >= num) {
					this.currentIndex = 0
				} else {
					this.currentIndex++
				}
			},
			onSwiperChange(e) {
				const { current, source } = e.detail;
			// 	const prevCurrent = this.prevCurrent; //存储旧current
				// this.prevCurrent = current; //赋值新current
				this.currentIndex = current //当前应展示current
			/**
			 * //     // 如果是手动切换
			//     if (source === 'touch') {
			// 		//关闭自动播放
			// 		this.isAutoplay = false
			// 		// 判断滑动方向 右滑
			// 		if (current > this.prevIndex) {
			// 			//判断连续右滑过程出现左滑，减少次数
			// 			if(current<prevCurrent){
			// 				this.i--
			// 			}else{
			// 				this.i++
			// 			}
			// 			//标记
			// 			this.isDirection = 'right'
			// 		  //判断滑动方向 左滑
			// 		} else if (current < this.prevIndex) {
			// 			//判断连续左滑过程出现右滑，增加次数
			// 			if(current>prevCurrent){
			// 				this.i++
			// 			}else{
			// 				this.i--
			// 			}
			// 			//标记
			// 			this.isDirection = 'left'
			// 		}else{
			// 			//如果过程滑到本来的页，则次数清0
			// 			this.i = 0
			// 		}
			// 		// 清除上一次的 setTimeout
			// 		if (this.manualSwitchTimeout) {
			// 		  clearTimeout(this.manualSwitchTimeout);
			// 		}
			// 		if(this.isDirection == 'right'){
			// 			// 设置新的 setTimeout
			// 			this.manualSwitchTimeout = setTimeout(() => {
			// 				//等待2秒更改回原来的轮播页
			// 				this.currentIndex = current - this.i;
			// 				//计数清0
			// 			    this.i =0
			// 				//重新计算 轮播图播放时间：当前音频剩余总时间 + 计时器时间 * 1000 / 轮播图剩余总页数
			// 				// console.log("总时间：",this.audioCtx.duration);
			// 				// console.log("当前播放时间：",this.timeAudio);
			// 				// console.log("总剩余时间：",(this.audioCtx.duration-this.timeAudio));
			// 				// console.log("轮播图总页数：",this.list.length);
			// 				// console.log("剩余总页数：",this.list.length - this.currentIndex);
			// 				const sumTime = (this.audioCtx.duration - this.timeAudio) * 1000		
			// 				this.imageInterval = sumTime / (this.list.length - this.currentIndex)
			// 				// console.log("计算当前每张图片轮播间隔时间：", this.imageInterval);
			// 				//开启自动播放
			// 				this.isAutoplay = true
			// 			}, 2000);
			// 		}else{
			// 			// 设置新的 setTimeout
			// 			this.manualSwitchTimeout = setTimeout(() => {
							
			// 				//等待2秒更改回原来的轮播页
			// 				this.currentIndex = current + -this.i; //--得正
			// 				//计数清0
			// 				this.i =0
			// 				//重新计算 轮播图播放时间：当前音频剩余总时间 + 计时器时间 * 1000 / 轮播图剩余总页数
			// 				const sumTime = (this.audioCtx.duration - this.timeAudio) * 1000
			// 				this.imageInterval = sumTime / (this.list.length - this.currentIndex)
			// 				//开启自动播放
			// 				this.isAutoplay = true
			// 			}, 2000);
			// 		}
			//       }else{
			// 		  //记录存储自动播放位置，用于判断是否往右滑还是往左滑
			// 		  this.prevIndex = current; 
			// 	  }
			*/
			    },
			//登录后回调
			succ(){
				if (this.audioCtx) {
					this.audioCtx.stop();
				    this.audioCtx.destroy()
				    this.audioCtx = null
				}
				this.getCourseDetails({course_id:this.course_id,chapter_id:this.chapter_id})
			},
			//点击播放/暂停
			handelAuto(){
				// this.isAutoplay = !this.isAutoplay
				if (this.isPlaying == false) {
					//音频暂停
					this.audioCtx.pause();
					this.isPlaying = true
				  } else {
					//音频开始播放
					this.audioCtx.play();
					this.isPlaying = false
				  }
			},
			getCourseDetails(data){
				CourseDetails(data).then((res)=>{
					if(res.data.code == 1){
						//ppt图片
						if(res.data.data.ppt_images.length > 0){
							this.list = res.data.data.ppt_images
						}
						//课件
						if(res.data.data.charperppt){
							this.downloadUrl = res.data.data.charperppt.file_url
						}
						//音频
						if(res.data.data.voice_data.length > 0){
							this.AudioVoiceList = res.data.data.voice_data
							this.audioSrc = res.data.data.voice_data[0].file //默认第一个音频
							//第一个音频高亮选择显示
							this.isActice = 0
							if (this.isPageVisible) {
								this.audioCtx = uni.createInnerAudioContext();
								this.audioCtx.src = encodeURI(this.audioSrc);
								this.audioCtx.seek(this.timeAudio); //息屏记录恢复播放位置
								//监听音频加载完成事件
								this.audioCtx.onCanplay(() => {
									//调用处理音频时长方法，计算图片平均时间展示
									// 获取音频的总时长（单位：秒）
									setTimeout(() => {
										if (this.audioCtx) {
											this.totalDuration = this.audioCtx.duration;
											// console.log('音频总时长:', this.totalDuration, '秒');	
												if(this.list.length!=0){
													// 计算每张图片的轮播间隔时间
													// this.imageInterval = ((this.audioCtx.duration+1) * 1000) / this.list.length;
													// console.log('每张图片的轮播间隔时间:', this.imageInterval, '毫秒');
												}
										}
									}, 1000)
									this.audioCtx.play();
								});
								 // 监听 onTimeUpdate 事件，实时获取当前播放时长
								  this.audioCtx.onTimeUpdate(() => {
									  this.timeAudio = this.audioCtx.currentTime // 获取当前播放时长
								  });
								//播放结束
								this.audioCtx.onEnded(() => {
									this.audioCtx.stop();
									//重新播放 循环播放
									this.audioCtx.seek(0); // 将音频位置重置到开始
									this.audioCtx.play();
								})
							}
							
						}
						//简介
						if(res.data.data.xiluedu_coupon){
							this.description = res.data.data.xiluedu_coupon.description
						}
						//文稿
						if(res.data.data.coursetopic){
							this.LessonList = decodeURIComponent(res.data.data.coursetopic.content)
						}
					}
				})
			},
			download() {
				uni.showLoading({
					title: '下载中'
				});
				//下载文件
				uni.downloadFile({ //只能是GET请求
					url: this.downloadUrl, //请求地址(后台返回的码流地址)
					success: (res) => {
						//下载成功
						if (res.statusCode === 200) {
							//保存文件
							let tempFile = res.tempFilePath;
							// 保存成功后，可以使用 openDocument 预览文件
							  uni.openDocument({
								filePath: tempFile,
								showMenu: true, // 是否可以分享
								fileType: 'pptx', // 指定文件类型
								success: (res) => {
								  uni.hideLoading();
								},
								fail: (e) => {
								  uni.showToast({
									title: '打开失败',
									icon: "error"
								  });
								}
							  });
							}
					},
					fail: (e) => {
						uni.showToast({
							title: '文件下载失败',
							icon: "error",
						})
					}
				});
 
 
			},
			handelVoice(data,index){
				this.isActice = index
				if (this.audioCtx) {
				  this.audioCtx.stop();
				  this.audioCtx.destroy()
				  this.audioCtx = null
				  // if (this.isAutoplay==false) {
				  //   this.isAutoplay = true;
				  //   this.isPlaying = false; 
				  // }
				  this.isPlaying = false; 
				  // 设置新的音频源
				  this.audioSrc = data.file
				   // 重新创建 audioCtx
				  this.audioCtx = uni.createInnerAudioContext();
				  this.audioCtx.src = encodeURI(this.audioSrc);
				 
				  this.audioCtx.seek(this.timeAudio);
				  this.audioCtx.onCanplay(() => {
				  	this.audioCtx.play();
				  });
				  // 监听 onTimeUpdate 事件，实时获取当前播放时长
				   this.audioCtx.onTimeUpdate(() => {
				  		this.timeAudio = this.audioCtx.currentTime // 获取当前播放时长
				   });
				  //播放结束
				  this.audioCtx.onEnded(() => {
					this.audioCtx.stop();
				  	//重新播放 循环播放
				  	this.audioCtx.seek(0); // 将音频位置重置到开始
				  	this.audioCtx.play();
				  })

				  this.audioCtx.onError((res) => {
				  	console.error('播放失败：', res);
				  	uni.showToast({
				  	title: '播放失败',
				  	icon: 'none'
				  	});
				  });
				}
				  
				
			},
			tabSelect(e) {
				this.current = e.currentTarget.dataset.id;
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60
			},
			swipeIndex(index) {
				// 通过tab组件回调点击切换的index同步swiper的current索引
				this.current = index.target.current
			},
		}
	}
</script>

<style lang="scss">
	/* 底部安全边距 start*/
	.tn-tabbar-height {
		min-height: 120rpx;
		height: calc(140rpx + env(safe-area-inset-bottom) / 2);
		height: calc(140rpx + constant(safe-area-inset-bottom));
	}
	.studyBox{
		position: relative;
		width: 100%;
		image{
			width: 100%;
		}
		/* Controls wrapper */
		.controls_postion {
		  position: absolute; /* 绝对定位 */
		  top: 50%; /* 垂直居中 */
		  left: 0;
		  right: 0;
		  display: flex; /* 使用弹性布局 */
		  justify-content: space-between; /* 水平方向上两端对齐 */
		  transform: translateY(-50%); /* 垂直居中对齐 */
		  z-index: 1; /* 确保按钮覆盖在图片上方 */
		  padding: 0 20rpx; /* 左右内边距 */
		}
		.hide{
			opacity: 0;
		}
		/* Left button */
		.left-back {
		  display: flex;
		  justify-content: center;
		  align-items: center;
		  width:55rpx ;
		  height: 55rpx;
		  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景色 */
		  color: #fff; /* 白色文字 */
		  padding: 10rpx; /* 内边距 */
		  border-radius: 50%; /* 圆形按钮 */
		  // cursor: pointer; /* 鼠标悬停时显示手型 */
		}
		
		/* Right button */
		.right-forword {
		  display: flex;
		  justify-content: center;
		  align-items: center;
		  width:55rpx ;
		  height: 55rpx;
		  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景色 */
		  color: #fff; /* 白色文字 */
		  padding: 10rpx; /* 内边距 */
		  border-radius: 50%; /* 圆形按钮 */
		  // cursor: pointer; /* 鼠标悬停时显示手型 */
		}
		.mask {
		  position: absolute;
		  top: 0;
		  left: 0;
		  width: 100%;
		  height: 520rpx;
		  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
		  display: flex;
		  justify-content: center;
		  align-items: center;
		}
		.controls {
			color: whitesmoke;
			font-size: 50px;
		}
	}
	.scroll-view-height {
		// width: 100vw;
		// height: 100vh;
		// white-space: nowrap;
		/* 页面高度减去包含状态栏、标题、tab组件的高度 */
		height: calc(100vh - var(--status-bar-height) - 178rpx);
		.content_text{
			background-color: #fff;
			.content_text_introductory{
				.active{
					border: 1px solid lightblue;
				}
				.description_box{
					margin: 5rpx;
					border: 1px solid lightgrey;
					border-radius: 10rpx;
					padding: 40rpx;
					line-height: 55rpx;
					// text-indent: 1em;
				}
				.Lesson_box{
					margin: 5rpx;
					border: 1px solid lightgrey;
					border-radius: 10rpx;
					padding: 40rpx;
					line-height: 55rpx;
					
				}
				.pptContent{
					border-radius: 10rpx;
					border: 1px solid lightgray;
				}
				padding: 20rpx;
				.pptBox{
					display: flex;
					align-items: center;
					.pptImg{
						width: 200rpx;
						height: 200rpx;
						img{
							border-radius: 20rpx;
							width: 100%;
							height: 100%;
						}
					}
				}
				.content_box{
					// width: 205rpx;
					margin: 10rpx 10rpx 10rpx 0;
					font-size: 22rpx;
					padding: 5px;
					background: #F5F7FA;
					.boxItem{
						.imgBox{
							width: 80rpx;
							height: 80rpx;
							margin-bottom: 5rpx;
							img{
								width: 100%;
								height: 100%;
							}
						}
						.cont-right{
							font-size: 20rpx;
							.man{
								padding: 5rpx;
								color: #1E7FFF;
								background-color: #ECF2FA;
							}
							.woman{
								padding: 5rpx;
								color: #FF481E;
								background-color: #F8F3F6;
							}
						}
					}
				}
				
			}
		}
	}
	
	// .wrap {
	// 	display: flex;
	// 	flex-direction: column;
	// 	height: calc(100vh - var(--window-top));
	// 	width: 100%;
	// 	white-space: nowrap;
	// }

	.list-content {
		background-color: #F4F4F4;
	}

</style>

